import axios, { AxiosInstance, AxiosError, InternalAxiosRequestConfig, AxiosResponse, RawAxiosRequestConfig } from "axios";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/config/serviceLoading";
import { LOGIN_URL } from "@/config";
import { ElMessage } from "element-plus";
import { ResultData } from "@/api/interface";
import { ResultEnum } from "@/enums/httpEnum";
import { checkStatus } from "./helper/checkStatus";
import { useUserStore } from "@/stores/modules/user";
import router from "@/routers";
export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
  noLoading?: boolean;
}

declare const window: any;
const VITE_API_URL = window.VITE_API_URL;
let _payloads: any = [];
let count: number = 0;
let urls: string[] = [];

let baseURL: string = "";
if (import.meta.env.VITE_USER_NODE_ENV === "development") {
  baseURL = import.meta.env.VITE_API_URL;
} else {
  baseURL = VITE_API_URL || import.meta.env.VITE_API_URL;
}

const config = {
  // 默认地址请求地址，可在 .env.** 文件中修改
  baseURL,
  // 设置超时时间
  timeout: ResultEnum.TIMEOUT as number,
  // 跨域时候允许携带凭证
  withCredentials: true
};

class RequestHttp {
  service: AxiosInstance;
  public constructor(config: RawAxiosRequestConfig) {
    // instantiation
    this.service = axios.create(config);
    /**
     * @description 请求拦截器
     * 客户端发送请求 -> [请求拦截器] -> 服务器
     * token校验(JWT) : 接受服务器返回的 token,存储到 vuex/pinia/本地储存当中
     */
    this.service.interceptors.request.use(
      (config: CustomAxiosRequestConfig) => {
        const userStore = useUserStore();
        // 当前请求不需要显示 loading，在 api 服务中通过指定的第三个参数: { noLoading: true } 来控制
        config.noLoading || showFullScreenLoading();
        if (config.headers && typeof config.headers.set === "function") {
          config.headers.set("token", userStore.token);
        }
        return config;
      },
      (error: AxiosError) => {
        return Promise.reject(error);
      }
    );

    /**
     * @description 响应拦截器
     *  服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
     */
    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        const { config, data } = response;
        const userStore = useUserStore();
        const payloadItem = _payloads.find(item => {
          if (item) return item.url === config.url;
          return false;
        });
        tryHideFullScreenLoading();
        count++;

        const contentType = response.headers["content-type"];
        if (
          (contentType && contentType.includes("application/octet-stream")) ||
          contentType.startsWith("image/") ||
          contentType.startsWith("application/pdf")
        ) {
          return data;
        } else {
          // 成功请求（在页面上除非特殊情况，否则不用处理失败逻辑）
          if (data.code !== -1) {
            if (data.code === 200) {
              return data;
            } else if (data.code === 403) {
              if (count === urls.length) {
                count = 0;
                urls = [];
                userStore.setToken("");
                router.replace(LOGIN_URL);
                ElMessage.error("会话超时,请重新登录");
                return Promise.reject(data);
              }
            } else {
              if (!payloadItem?.payload?.noTips) ElMessage.error(data.message);
              return Promise.reject(data);
            }
          } else {
            if (!payloadItem?.payload?.noTips) ElMessage.error(data.message);
            return Promise.reject(data);
          }
        }
      },
      async (error: AxiosError) => {
        const { response } = error;
        tryHideFullScreenLoading();
        count++;
        // 请求超时 && 网络错误单独判断，没有 response
        if (error.message.indexOf("timeout") !== -1) ElMessage.error("请求超时！请您稍后重试");
        if (error.message.indexOf("Network Error") !== -1) ElMessage.error("网络错误！请您稍后重试");
        // 根据服务器响应的错误状态码，做不同的处理
        if (response) checkStatus(response.status);
        // 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
        if (!window.navigator.onLine) router.replace("/500");
        return Promise.reject(error);
      }
    );
  }

  /**
   * @description 常用请求方法封装
   */
  get<T>(url: string, params?: object, _object = {}, payload?: object): Promise<ResultData<T>> {
    _payloads.push({
      url,
      payload
    });
    urls.push(url);
    return this.service.get(url, { params, ..._object });
  }
  post<T>(url: string, params?: object | string, _object = {}, payload?: object): Promise<ResultData<T>> {
    _payloads.push({
      url,
      payload
    });
    urls.push(url);
    return this.service.post(url, params, _object);
  }
  put<T>(url: string, params?: object, _object = {}, payload?: object): Promise<ResultData<T>> {
    _payloads.push({
      url,
      payload
    });
    urls.push(url);
    return this.service.put(url, params, _object);
  }
  delete<T>(url: string, params?: any, _object = {}, payload?: object): Promise<ResultData<T>> {
    _payloads.push({
      url,
      payload
    });
    urls.push(url);
    return this.service.delete(url, { params, ..._object });
  }
  download(url: string, params?: object, _object = {}, payload?: object): Promise<BlobPart> {
    _payloads.push(payload);
    urls.push(url);
    return this.service.post(url, params, { ..._object, responseType: "blob" });
  }
  jsonp(url) {
    return new Promise(resolve => {
      window.callback = result => {
        resolve(result);
      };
      const JSONP = document.createElement("script");
      JSONP.type = "text/javascript";
      JSONP.src = url;
      document.getElementsByTagName("head")[0].appendChild(JSONP);
      setTimeout(() => {
        document.getElementsByTagName("head")[0].removeChild(JSONP);
      }, 500);
    });
  }
}

export default new RequestHttp(config);
